package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;

/**
 * Servlet implementation class ChangePasswordServlet
 */
@WebServlet("/ChangePassword")
public class ChangePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChangePasswordServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String confirmOldPass = request.getParameter("oldPass");
		String newPass = request.getParameter("newPass");
		String confirmNewPass = request.getParameter("confirmNewPass");
		String username = (String) request.getSession()
				.getAttribute("username");
		String password = (String) request.getSession()
				.getAttribute("password");

		Connection conn = null;
		PreparedStatement stmt = null;
		String sql = "update user " + "set Password=? where UserName=?";
		if (!confirmOldPass.equals(password)) {
			
			request.setAttribute("changePwMsg", "You entered wrong password. Please try again");
			request.getRequestDispatcher("ChangePassword.jsp").forward(request, response);
			
		} else if (!newPass.equals(confirmNewPass)) {
			
			request.setAttribute("changePwMsg", "Confirm New Password and New Password are mismatch! Please try again");
			request.getRequestDispatcher("ChangePassword.jsp").forward(request, response);
			
		} else {
			try {
				conn = UserManagementDbConnector.getConnection();
				stmt = conn.prepareStatement(sql);
				stmt.setString(1, newPass);
				stmt.setString(2, username);
				stmt.executeUpdate();
				request.getSession().setAttribute("password", newPass);
				request.getSession().setAttribute("changePwMsg", "You have succesfully changed your password!");
				request.getRequestDispatcher("ChangePassword.jsp").forward(request, response);
				
				stmt.close();
				conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
	}

}
